package cn.stronglink.assetmanage.business.inventory.view.goods;

import android.app.Dialog;
import android.content.DialogInterface;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import Scaner.scan.IScanerListener;
import Scaner.scan.TimerInfraraedScaner;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.inventory.model.InventoryDetailModel;
import cn.stronglink.assetmanage.business.inventory.presenter.InventoryDetailPresenter;
import cn.stronglink.assetmanage.business.inventory.view.detail.InventoryDetailView;
import cn.stronglink.assetmanage.business.search.presenter.AssisChangePresenter;
import cn.stronglink.assetmanage.business.setting.ipset.SystemFragment;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.InventoryDetailDao;
import cn.stronglink.assetmanage.dao.ModelDao;
import cn.stronglink.assetmanage.entity.Brand;
import cn.stronglink.assetmanage.entity.Cabinet;
import cn.stronglink.assetmanage.entity.DataCenter;
import cn.stronglink.assetmanage.entity.Department;
import cn.stronglink.assetmanage.entity.Inventory;
import cn.stronglink.assetmanage.entity.InventoryDetail;
import cn.stronglink.assetmanage.entity.Model;
import cn.stronglink.assetmanage.entity.Node;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.Type;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.SpinnerShowUtil;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import cn.stronglink.assetmanage.widget.MenuOrderDialog;
import cn.stronglink.assetmanage.widget.ViewPagerFragment;

import static cn.stronglink.assetmanage.R.id.sp_inventory_location;

/**
 * 盘盈数据
 * Created by yuzhantao on 2018/6/23.
 * 商品详情编辑界面
 */

public class GoodsDetailEditFragment extends ViewPagerFragment implements View.OnClickListener {
    private final static byte SCAN_SN = 1;
    private final static byte SCAN_RFID = 2;

    private Spinner spInventoryGoodsBranch;    // 品牌
    private Spinner spInventoryGoodsClass;       // 产品分类
    private Spinner spRoom;     // 存放地点
    private Spinner spGoodsModel; // 设备型号
    private Spinner sp_select_state;//资产状态：在库，在架，不处理
    private Spinner sp_inventory_cabinet;//机柜
    private Button butSave;
    //默认不处理
    private int inventoryAssetStatus = -1;
    private InventoryDetail inventoryDetail;
    private InventoryDetailModel inventoryDetailModel;
    private GoodsDetailEditView goodsDetailEditView;
    private EditText tv_inventory_asset_name, tv_inventory_sn_no, tv_inventory_rfid_no, et_inventory_u, et_inventory_assetno;
    private Node mNode;
    private TimerInfraraedScaner scaner; // 条码扫描器
    private byte scanTarget;     // 扫描目标
    private TextView textView;
    private Inventory mInventory;
    Dialog mDialog;

    TextView tv_data_base_0;
    TableRow tr_base_data_1;
    TableRow tr_base_data_2;
    TableRow tr_base_data_3;
    TableRow tr_base_data_4;
    TableRow tr_zaijia_data;
    private String zichanLeiBie, pinpai, didian, shebeixinghao, jigui;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_inventory_goods_detail_edit, container, false);
        try {
            mDialog = CustomProgressDialog.createLoadingDialog(this.getContext(), "正在加载中...");
//            mDialog.show();
            initViewAndData(rootView);
//            mDialog.cancel();
        } catch (Exception e) {
            Toast.makeText(this.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        return rootView;
    }

    private void initViewAndData(View view) {

        tv_inventory_asset_name = view.findViewById(R.id.tv_inventory_asset_name);
        tv_inventory_sn_no = view.findViewById(R.id.tv_inventory_sn_no);
        tv_inventory_rfid_no = view.findViewById(R.id.tv_inventory_rfid_no);
        et_inventory_u = view.findViewById(R.id.et_inventory_u);
        et_inventory_assetno = view.findViewById(R.id.et_inventory_assetno);
        tv_inventory_sn_no.setOnClickListener(this);
        tv_inventory_rfid_no.setOnClickListener(this);
        inventoryDetailModel = new InventoryDetailModel();
        goodsDetailEditView = new GoodsDetailEditView(this, view);

        Bundle bundle = getArguments();
        if (bundle != null) {
            String assetRfid = bundle.getString(Constants.RFID);
            String orderId = bundle.getString(Constants.CHECK_IN_DETAIL_NO);
            GoodsDetailEditFragment.this.inventoryDetail =
                    inventoryDetailModel.getInventoryDetailByOrderAndRfid(orderId, assetRfid);
            this.mInventory = inventoryDetailModel.getInventoryById(orderId);
            //在数据库里没有找到数据
            if (inventoryDetail == null) {
                inventoryDetail = new InventoryDetail();
                inventoryDetail.setOrderNo(orderId);
                inventoryDetail.setRfidNo(assetRfid);
            }
        } else {
            goodsDetailEditView.showToast(getString(R.string.get_no_data));
            return;
        }
        //初始化资源状态：
        initInventoryDetailState(view);
        tv_inventory_asset_name.setText(inventoryDetail.getAssetName());
        tv_inventory_sn_no.setText(inventoryDetail.getSerialNo());
        tv_inventory_rfid_no.setText(inventoryDetail.getRfidNo());

        tv_inventory_asset_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                inventoryDetail.setAssetName(tv_inventory_asset_name.getText().toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        tv_inventory_sn_no.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                inventoryDetail.setSerialNo(tv_inventory_sn_no.getText().toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        tv_inventory_rfid_no.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                inventoryDetail.setRfidNo(tv_inventory_rfid_no.getText().toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        et_inventory_u.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                inventoryDetail.setStartU(Integer.valueOf(et_inventory_u.getText().toString()));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        et_inventory_assetno.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                inventoryDetail.setAssetNo((et_inventory_assetno.getText().toString()));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        // 存放地点
        List<Room> roomList = inventoryDetailModel.getRoomData();
        ArrayAdapter<Room> roomArrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, roomList);
        spRoom = view.findViewById(sp_inventory_location);
        spRoom.setAdapter(roomArrayAdapter);
        spRoom.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Room room = (Room) spRoom.getSelectedItem();
                if (room.getId_() == null || room.getId_().isEmpty()) {
                    return;
                }
                GoodsDetailEditFragment.this.inventoryDetail.setRoomId(Long.valueOf(room.getId_()));
                GoodsDetailEditFragment.this.inventoryDetail.setRoomId_(room.getId_());
                GoodsDetailEditFragment.this.inventoryDetail.setRoomName(room.getName());
                didian = room.getName();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        final List<Model> modelList = inventoryDetailModel.getModelList();
        final ArrayAdapter<Model> modelArrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, modelList);
        spGoodsModel = view.findViewById(R.id.tv_inventory_model_name);
        spGoodsModel.setAdapter(modelArrayAdapter);
        spGoodsModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Model model = (Model) spGoodsModel.getSelectedItem();
                if (model.getId_() == null || model.getId_().isEmpty()) {
                    return;
                }
                GoodsDetailEditFragment.this.inventoryDetail.setModelId(Long.valueOf(model.getId_()));
                GoodsDetailEditFragment.this.inventoryDetail.setModelId_(model.getId_());
                GoodsDetailEditFragment.this.inventoryDetail.setModelName(model.getName());
                shebeixinghao = model.getName();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        // 设置品牌
        List<Brand> brandList = inventoryDetailModel.getBrandData();
        ArrayAdapter<Brand> brandArrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, brandList);
        spInventoryGoodsBranch = view.findViewById(R.id.sp_inventory_brand_name);
        spInventoryGoodsBranch.setAdapter(brandArrayAdapter);
        spInventoryGoodsBranch.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Brand brand = (Brand) spInventoryGoodsBranch.getSelectedItem();
                if (brand.getId_() == null || brand.getId_().isEmpty()) {
                    return;
                }
                GoodsDetailEditFragment.this.inventoryDetail.setBrandId(Long.valueOf(brand.getId_()));
                GoodsDetailEditFragment.this.inventoryDetail.setBrandId_(brand.getId_());
                GoodsDetailEditFragment.this.inventoryDetail.setBrandName(brand.getName());

                List<Model> models = DaoManager.getDaoSession(GoodsDetailEditFragment.this.getContext())
                        .getModelDao().queryBuilder().where(
                                ModelDao.Properties.BrandId_.eq(GoodsDetailEditFragment.this.inventoryDetail.getBrandId()),
                                ModelDao.Properties.TypeId_.eq(GoodsDetailEditFragment.this.inventoryDetail.getTypeId())).list();
                if (models != null) {
                    modelArrayAdapter.clear();
                    modelArrayAdapter.addAll(models);
                }
                pinpai = brand.getName();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        List<Type> goodsClassList = inventoryDetailModel.getTypeData();
        ArrayAdapter<Type> goodsClassArrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, goodsClassList);
        spInventoryGoodsClass = view.findViewById(R.id.tv_inventory_goods_detail_edit_asset_class);
        spInventoryGoodsClass.setAdapter(goodsClassArrayAdapter);
        spInventoryGoodsClass.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Type t = (Type) spInventoryGoodsClass.getSelectedItem();
                if (t.getId_() == null || t.getId_().isEmpty()) {
                    return;
                }
                GoodsDetailEditFragment.this.inventoryDetail.setTypeId(Long.valueOf(t.getId_()));
                GoodsDetailEditFragment.this.inventoryDetail.setTypeId_(t.getId_());
                GoodsDetailEditFragment.this.inventoryDetail.setTypeName(t.getName());
                zichanLeiBie = t.getName();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                List<Model> models = DaoManager.getDaoSession(GoodsDetailEditFragment.this.getContext())
                        .getModelDao().queryBuilder().where(
                                ModelDao.Properties.BrandId_.eq(GoodsDetailEditFragment.this.inventoryDetail.getBrandId()),
                                ModelDao.Properties.TypeId_.eq(GoodsDetailEditFragment.this.inventoryDetail.getTypeId())).list();
                if (models != null) {
                    modelArrayAdapter.clear();
                    modelArrayAdapter.addAll(models);
                }
            }
        });

        //设置机柜
        List<Cabinet> cabinetList = inventoryDetailModel.getCabinet();
        ArrayAdapter<Cabinet> cabinetArrayAdapter = new ArrayAdapter<>(getActivity()
                , android.R.layout.simple_dropdown_item_1line, cabinetList);
        sp_inventory_cabinet = view.findViewById(R.id.sp_inventory_cabinet);
        sp_inventory_cabinet.setAdapter(cabinetArrayAdapter);
        sp_inventory_cabinet.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Cabinet t = (Cabinet) sp_inventory_cabinet.getSelectedItem();
                if (t.getId_() == null || t.getId_().isEmpty()) {
                    return;
                }
                GoodsDetailEditFragment.this.inventoryDetail.setRackId(Long.valueOf(t.getId_()));
                GoodsDetailEditFragment.this.inventoryDetail.setRackId_(t.getId_());
                GoodsDetailEditFragment.this.inventoryDetail.setRackName(t.getAssetName());
                jigui = t.getAssetName();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        if (mInventory != null) {
            setSpinnerItemSelectedByValue(spGoodsModel, this.mInventory.getRoomName());
            didian = this.mInventory.getRoomName();
            inventoryDetail.setRoomName(didian);
            if (didian != null && !"".equals(didian)) {
                String roomId_ = inventoryDetailModel.getRoomId_(didian);
                inventoryDetail.setRoomId(Long.valueOf(roomId_));
                inventoryDetail.setRoomId_(roomId_);
            }
        }
        butSave = view.findViewById(R.id.btn_edit_goods_finish);
        butSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (tv_inventory_asset_name.getText().toString().isEmpty()) {
                        Toast.makeText(GoodsDetailEditFragment.this.getContext(), "请输入资产名称", Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (tv_inventory_sn_no.getText().toString().isEmpty()) {
                        Toast.makeText(GoodsDetailEditFragment.this.getContext(), "请输入SN号", Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (tv_inventory_rfid_no.getText().toString().isEmpty()) {
                        Toast.makeText(GoodsDetailEditFragment.this.getContext(), "请输入rfid", Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (inventoryAssetStatus == 2) {
                        if (et_inventory_u.getText().toString().isEmpty()) {
                            Toast.makeText(GoodsDetailEditFragment.this.getContext(), "请输入u位值", Toast.LENGTH_LONG).show();
                            return;
                        }
                        if (jigui == null || "".equals(zichanLeiBie)) {
                            Toast.makeText(GoodsDetailEditFragment.this.getContext(), "请选择机柜值", Toast.LENGTH_LONG).show();
                            return;
                        }
                    }


                    if (zichanLeiBie == null || "".equals(zichanLeiBie)) {
                        Toast.makeText(GoodsDetailEditFragment.this.getContext(), "请选择资产类别", Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (shebeixinghao == null || "".equals(shebeixinghao )) {
                        Toast.makeText(GoodsDetailEditFragment.this.getContext(), "请选择设备型号", Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (pinpai == null || "".equals(pinpai)) {
                        Toast.makeText(GoodsDetailEditFragment.this.getContext(), "请选择品牌", Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (didian == null || "".equals(didian)) {
                        Toast.makeText(GoodsDetailEditFragment.this.getContext(), "请选择地点", Toast.LENGTH_LONG).show();
                        return;
                    }

                    mDialog.show();
                    DaoManager.getDaoSession(GoodsDetailEditFragment.this.getContext()).insertOrReplace(inventoryDetail);
                    Toast.makeText(
                            GoodsDetailEditFragment.this.getContext(),
                            "保存完成",
                            Toast.LENGTH_LONG
                    ).show();
                    mDialog.hide();

                    GoodsDetailEditFragment.this.getActivity().onBackPressed();
                } catch (Exception e) {
                    Toast.makeText(
                            GoodsDetailEditFragment.this.getContext(),
                            e.getMessage(),
                            Toast.LENGTH_LONG
                    ).show();
                }
            }
        });

        scaner = new TimerInfraraedScaner(this.getContext());
        scaner.setScanerListener(new IScanerListener() {
            @Override
            public void onScaning(List<String> data) {
                if (scanTarget == SCAN_SN) {
                    tv_inventory_sn_no.setText(data.get(0));
                } else if (scanTarget == SCAN_RFID) {
                    tv_inventory_rfid_no.setText(data.get(0));
                }
            }
        });
    }

    //盘盈的资产填写资料时，（在库、在架、不处理），在库填基础数据、在架填机柜和u位、不处理不限制。默认显示不处理
    //-1：不处理，1：在库，2：上架
    private void initInventoryDetailState(View view) {
        tv_data_base_0 = view.findViewById(R.id.tv_data_base_0);
        tr_base_data_1 = view.findViewById(R.id.tr_base_data_1);
        tr_base_data_2 = view.findViewById(R.id.tr_base_data_2);
        tr_base_data_3 = view.findViewById(R.id.tr_base_data_3);
        tr_base_data_4 = view.findViewById(R.id.tr_base_data_4);
        tr_zaijia_data = view.findViewById(R.id.tr_zaijia_data);
        inventoryDetail.setStatus(inventoryAssetStatus);
        List<String> stateList = new ArrayList<>();
        stateList.add("不处理");
        stateList.add("在库");
        stateList.add("在架");
        ArrayAdapter<String> selectStateAdapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_dropdown_item_1line, stateList);
        sp_select_state = view.findViewById(R.id.sp_select_state);
        sp_select_state.setAdapter(selectStateAdapter);
        sp_select_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedItem = (String) sp_select_state.getSelectedItem();
                if (selectedItem == null || selectedItem.isEmpty()) {
                    return;
                }
                showDataView(selectedItem);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void showDataView(String selectedItem) {
        switch (selectedItem) {
            case "在库":
                baseDataView(true);
                zaiJiaDataView(false);
                inventoryAssetStatus = 1;
                break;
            case "在架":
                baseDataView(true);
                zaiJiaDataView(true);
                inventoryAssetStatus = 2;
                break;
            case "不处理":
                baseDataView(true);
                zaiJiaDataView(true);
                inventoryAssetStatus = -1;
                break;
            default:
                break;
        }
        inventoryDetail.setStatus(inventoryAssetStatus);
    }

    private void baseDataView(boolean isShow) {
        if (isShow) {
            tv_data_base_0.setVisibility(View.VISIBLE);
            tv_inventory_asset_name.setVisibility(View.VISIBLE);
            tr_base_data_1.setVisibility(View.VISIBLE);
            tr_base_data_2.setVisibility(View.VISIBLE);
            tr_base_data_3.setVisibility(View.VISIBLE);
            tr_base_data_4.setVisibility(View.VISIBLE);
        } else {
            tv_data_base_0.setVisibility(View.INVISIBLE);
            tv_inventory_asset_name.setVisibility(View.INVISIBLE);
            tr_base_data_1.setVisibility(View.GONE);
            tr_base_data_2.setVisibility(View.GONE);
            tr_base_data_3.setVisibility(View.GONE);
            tr_base_data_4.setVisibility(View.GONE);
        }
    }

    private void zaiJiaDataView(boolean isShow) {
        if (isShow) {
            tr_zaijia_data.setVisibility(View.VISIBLE);
        } else {
            tr_zaijia_data.setVisibility(View.GONE);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            if (scaner != null) {
                scaner.stop();
                scaner.setScanerListener(null);
                scaner.destory();
            }
        } catch (Exception e) {
            Toast.makeText(this.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        try {
            switch (v.getId()) {
                case R.id.tv_inventory_sn_no:
                    scanTarget = SCAN_SN;
                    if (scaner != null) {
                        scaner.playSingle();
                    }
                    break;
                case R.id.tv_inventory_rfid_no:
                    scanTarget = SCAN_RFID;
                    if (scaner != null) {
                        scaner.playSingle();
                    }
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            Toast.makeText(this.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 根据值, 设置spinner默认选中:
     *
     * @param spinner
     * @param value
     */
    private void setSpinnerItemSelectedByValue(Spinner spinner, String value) {
        SpinnerAdapter apsAdapter = spinner.getAdapter(); //得到SpinnerAdapter对象
        int k = apsAdapter.getCount();
        for (int i = 0; i < k; i++) {
            if (value != null && value.equals(apsAdapter.getItem(i).toString())) {
                spinner.setSelection(i, true);// 默认选中项
                break;
            }
        }
    }
}
